package com.powernode.filter;

import com.alibaba.fastjson.JSONObject;
import com.powernode.constant.AuthConstants;
import com.powernode.model.SecurityUser;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @create: 2024/7/16
 * @author: gyhe10
 * @description: TOKEN转换过滤器
 **/

@Component
public class TokenTranslationFilter extends OncePerRequestFilter {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * token转换过滤器
     * 只负责处理携带token的请求，解析token获取用户信息
     * 没有携带token的请求，交给SpringSecurity资源配置类中的处理器
     *
     * 1. 获取token
     * 2. 判断token是否有值
     *      有：解析token获取用户信息，并将用户信息转换为SpringSecurity框架认识的用户信息对象（UserDetails实现类）,再将该用户信息对象放入到当前资源服务器的容器中
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从请求头中获取token
        String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
        if (StringUtils.hasText(authorizationValue)) {
            String token = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
            // 判断token是否有值
            if (StringUtils.hasText(token)) {

                // token续签
                // 从redis中获取当前token的过期时间
                Long expire = stringRedisTemplate.getExpire(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                // 判断是否超过约定的阈值
                if (expire < AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME) {
                    // 续签
                    stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX + token, AuthConstants.TOKEN_TIME, TimeUnit.SECONDS);
                }

                // 从redis中获取JSON字符串格式的用户信息
                String userJsonStr = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                // 将JSON字符串转换为UserDetails实现类
                SecurityUser securityUser = JSONObject.parseObject(userJsonStr, SecurityUser.class);
                // 处理当前用户权限
                // Set<SimpleGrantedAuthority> collect = securityUser.getPerms().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
                Set<SimpleGrantedAuthority> collect = new HashSet<>();
                HashSet<String> strings = new HashSet<>();
                strings.add("");
                if (!securityUser.getPerms().equals(strings)) {
                    collect = securityUser.getPerms().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
                }
                // 创建UsernamePasswordAuthenticationToken对象
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, collect);
                // 将UserDetails实现类放入到当前资源服务器的容器中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
